<template>
  <el-button class="mb5" plain type="primary" @click="handleAdd">
    <template #icon>
      <i-ep-plus/>
    </template>
    新增
  </el-button>
  <el-button class="mb5" type="primary" @click="listHisDiagnosisFun">
    <template #icon>
      <i-ep-search/>
    </template>
    刷新
  </el-button>
  <el-table v-loading="loading" :border="true" :data="hisDiagnosisList" :header-cell-style="$headerCellStyle"
            :stripe="true"
            height="180" highlight-current-row>
    <el-table-column :align="'center'" label="西/中医诊断" prop="type" width="100">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <dict-data-tag :options="dictDataMap['chinese_western_type']" :value="scope.row.type"/>
        </template>
        <template v-else>
          <el-select v-model="form.type" placeholder="请选择" style="width: 100%;">
            <el-option v-for=" dict in dictDataMap['chinese_western_type'] " :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </template>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" label="诊断类型" prop="diagnosisType" width="120">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <dict-data-tag :options="dictDataMap['diagnosis_type']" :value="scope.row.diagnosisType"/>
        </template>
        <template v-else>
          <el-select v-model="form.diagnosisType" placeholder="请选择" style="width: 100%;">
            <el-option v-for=" dict in dictDataMap['diagnosis_type'] " :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </template>

      </template>
    </el-table-column>
    <el-table-column :align="'center'" label="名称" prop="icdName">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <span> {{ scope.row.icdName }}</span>
        </template>

        <el-input v-else-if="scope.row.isEdit && scope.row.isShow" v-model="form.icdName"
                  @focus="isShowItemNameFocus(scope.$index, scope.row)">
        </el-input>
        <automatic-completion v-else ref="itemAutomatic" :dict-array="dictArray" :table-body-list="tableBodyList"
                              :table-head-list="tableHeadList" :title="itemTitle" :width="900"
                              style="width: 100%;" @itemNameInput="itemNameInput"
                              @rowClick="rowClick($event, scope.$index, scope.row)"/>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" label="编码" prop="icdCode" width="200">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <span> {{ scope.row.icdCode }}</span>
        </template>
        <template v-else>
          <span> {{ form.icdCode }}</span>
        </template>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" label="确诊标识" prop="type" width="100">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <dict-data-tag :options="dictDataMap['diagnose_state_type']" :value="scope.row.isDiagnose"/>
        </template>
        <template v-else>
          <el-select v-model="form.isDiagnose" placeholder="请选择" style="width: 100%;">
            <el-option v-for=" dict in dictDataMap['diagnose_state_type'] " :key="dict.dictValue"
                       :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </template>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" label="诊断医生" prop="diagnosisDoctorName" width="99">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <span> {{ scope.row.diagnosisDoctorName }}</span>
        </template>
        <template v-else>
          <span> {{ form.diagnosisDoctorName }}</span>
        </template>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" label="排序(1:主诊断)" prop="sort" width="120">
      <template #default="scope">
        <template v-if="scope.row.id && !scope.row.isEdit">
          <span> {{ scope.row.sort }}</span>
        </template>
        <template v-else>
          <span><el-input v-model="form.sort" clearable placeholder="请输入排序" type="number"/></span>
        </template>
      </template>
    </el-table-column>
    <el-table-column :align="'center'" fixed="right" label="操作" width="120">
      <template #default="scope">
        <template v-if="scope.row.isEdit">
          <el-tooltip class="item" content="保存诊断"
                      effect="dark"
                      placement="top">
            <el-button circle type="primary" @click="handleSave(scope.$index, scope.row)">
              <svg-icon :icon-class="'save'"/>
            </el-button>
          </el-tooltip>
        </template>
        <template v-else>
          <el-tooltip circle class="item" content="编辑"
                      effect="dark"
                      placement="top">
            <el-button circle type="success" @click="handleUpdate(scope.$index, scope.row)">
              <i-ep-edit/>
            </el-button>
          </el-tooltip>
        </template>
        <el-tooltip circle class="item" content="删除"
                    effect="dark"
                    placement="top">
          <el-button circle type="danger" @click="handleDelete(scope.$index, scope.row)">
            <i-ep-delete/>
          </el-button>
        </el-tooltip>
      </template>
    </el-table-column>
  </el-table>
</template>

<script lang="ts" setup>
import {useDictStoreHook} from "@/store/modules/dict"
import {useUserStoreHook} from "@/store/modules/user"
import {addHisDiagnosis, delHisDiagnosis, listHisDiagnosis, updateHisDiagnosis} from "@/api/diagnosis/hisDiagnosis"
import {getAutoHisIcd} from "@/api/base/hisDataIcd10"
import {icd10List, jsonStrInObj} from "@/utils/autoComplete"

const dictStore = useDictStoreHook()
let dictDataMap = ref(dictStore.isTypeGetData('diagnosis_type', 'chinese_western_type', 'diagnose_state_type'))
const useUserStore = useUserStoreHook()
// 项目选择自动补全窗体名称
const itemTitle = ref('诊断选择')
// 项目选择自动补全表格表头
const tableHeadList = ref<any>(jsonStrInObj(icd10List))
// 项目选择自动补全表格数据
const tableBodyList = ref<any>([])
// 项目选择自动补全字典数组
const dictArray = ref(['chinese_western_type'])
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
const props = defineProps({
  clinicId: String,
  patientId: String
})
const loading = ref(false)
const itemAutomatic = ref()
const hisDiagnosisList = ref<any>([])
const form = ref<any>({
  isDiagnose: '1'
})
listHisDiagnosisFun()

function listHisDiagnosisFun() {
  listHisDiagnosis({clinicId: props.clinicId, inoroutFlag: '4'}).then((res: any) => {
    hisDiagnosisList.value = res.data
  })
}

/** 新增诊断 */
function handleAdd() {
  const lastRow = hisDiagnosisList.value.length > 0 ? hisDiagnosisList.value[hisDiagnosisList.value.length - 1] : {isEdit: false}
  if (lastRow.isEdit) {
    return ElMessage.error("请保存上一条诊断后再添加")
  }
  hisDiagnosisList.value.push({
    isEdit: true,
    id: ''
  })
  form.value.type = '1'
  form.value.isDiagnose = '1'
  form.value.diagnosisType = '5'
  form.value.id = ""
  form.value.sort = hisDiagnosisList.value.length
  // form.value.isEdit = true
}

function handleUpdate(index: number, row: any) {
  const isEditIndex = hisDiagnosisList.value.findIndex(item => {
    return item.isEdit === true
  })
  if (isEditIndex > -1) {
    return ElMessage.warning(`请先保存第${isEditIndex + 1}行诊断后再编辑其他诊断`)
  }
  hisDiagnosisList.value[index].isEdit = true
  row.isShow = true
  form.value = row
}

function handleSave(index: number, _row: any) {
  // form.value = row
  if (!form.value.icdName) {
    return ElMessage.error("请选择诊断后再保存")
  }
  // (formRef.value as any).validate(valid => {
  //     if (valid) {
  ElMessageBox.confirm('确定要保存吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    form.value.orgId = userInfo.orgId
    form.value.inoroutFlag = '4'
    form.value.isUpdateDoctorId = "Y"
    hisDiagnosisList.value[index].isEdit = false
    if (form.value.id != "") {
      updateHisDiagnosis(form.value).then(() => {
        ElMessage.success("修改成功");
        listHisDiagnosisFun()
      })
    } else {
      addHisDiagnosis(form.value).then(() => {
        ElMessage.success("保存成功");
        listHisDiagnosisFun()
      })
    }
  }).catch(() => {
    listHisDiagnosisFun()
  })
  // }
  // });
}

/** 删除按钮操作 */
function handleDelete(index: number, row: any) {
  if (row.id) {
    const _ids = row.id
    const icdName = row.icdName
    ElMessageBox.confirm('是否确认删除患者诊断名称为"' + icdName + '"的数据项？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      loading.value = true;
      delHisDiagnosis(_ids).then(() => {
        loading.value = false;
        listHisDiagnosisFun();
        ElMessage.success("删除成功");
      })
    }).catch(() => {
      loading.value = false;
    })
  } else {
    hisDiagnosisList.value.splice(index, 1)
  }
}

/**
 * 清空历史诊断列表
 */
function clearHisDiagnosisList() {
  hisDiagnosisList.value = []
}

/** 项目名称自动补全检索 */
function itemNameInput(event) {
  debugger
  form.value.itemName = event
  getAutoHisIcdFun()
}

function getAutoHisIcdFun() {
  const param = {
    chineseWesternType: form.value.type,
    orgId: userInfo.orgId,
    itemInfo: form.value.itemName

  }
  getAutoHisIcd(param).then(res => {
    tableBodyList.value = res.data
    itemAutomatic.value.init()
  })
}

/** icd10自动补全点击事件 */
function rowClick(e: any, _index: number, row: any) {
  nextTick(() => {
    if (e) {
      nextTick(() => {
        itemAutomatic.value.closePopover()
      })
      form.value.itemInfo = e.zhongwenMingcheng
      form.value.icdName = e.zhongwenMingcheng
      form.value.icdCode = e.code
      form.value.orgId = e.orgId
      form.value.type = e.chineseWesternType
      form.value.clinicId = props.clinicId
      form.value.patientId = props.patientId
      // form.value.diagnosisType = obj.diagnosisType
      row.isShow = true
    }
  })
}


/**
 * 自动补全上边input获得焦点事件
 * @param _index
 * @param row
 */
function isShowItemNameFocus(_index: number, row: any) {
  row.isShow = false
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(form.value.icdName)
    itemAutomatic.value.focusInput()
  })
}


defineExpose({
  clearHisDiagnosisList
})
</script>

<script lang="ts">
export default {
  name: "diagnosisTable"
}
</script>
